﻿using B.S.DataBase.MyProject.Domain.RBAC;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyRead.API.Appicant.Command.Menus;
using B.S.DataBase.MyRead.API.DTOs;
using MediatR;
using System;
using System.Security.Cryptography;

namespace B.S.DataBase.MyRead.API.Appicant.CommandHandler.Menus
{
    public class FiveTableCommandHandler : IRequestHandler<FiveTableCommand, APIResult<List<FiveTableDTO>>>
    {
        private readonly IBaseRepository<User> userRep;
        private readonly IBaseRepository<Role> roleRep;
        private readonly IBaseRepository<UserRole> urRep;
        private readonly IBaseRepository<Menu> menuRep;
        private readonly IBaseRepository<RoleMenu> ruRep;

        public FiveTableCommandHandler(IBaseRepository<User> userRep, IBaseRepository<Role> roleRep, IBaseRepository<UserRole> urRep, IBaseRepository<Menu> menuRep, IBaseRepository<RoleMenu> ruRep)
        {
            this.userRep = userRep;
            this.roleRep = roleRep;
            this.urRep = urRep;
            this.menuRep = menuRep;
            this.ruRep=ruRep;
        }
        public async Task<APIResult<List<FiveTableDTO>>> Handle(FiveTableCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<FiveTableDTO>> result=new APIResult<List<FiveTableDTO>>();
            

            var getRoleId = urRep.GetAll().Result.Where(x => x.UserId == request.UserId);

            int[] roleId= getRoleId.Select(x=>x.RoleId).ToArray();

            var getRoleMenu = ruRep.GetAll().Result.Where(x => roleId.Contains(x.RoleId));

            var list = from a in getRoleMenu
                       join b in await menuRep.GetAll() on a.MenuId equals b.MenuId
                       select new FiveTableDTO
                       {
                           MenuId = a.MenuId,
                           MenuName=b.MenuName,
                           PId=b.PId,
                           Url=b.Url,
                           RoleId=a.RoleId,
                           RMId=a.RMId,
                       };
            int num = list.Count();
            result.Code = APIEnum.查询成功;
            result.Msg = APIEnum.查询成功 + $"共查询到{num}条";
            result.data = list.ToList();
            return await Task.FromResult(result);
        }
    }
}
